package com.lrc.dentalbackend.controller;

import com.lrc.dentalbackend.common.ResponseResult;
import com.lrc.dentalbackend.service.RecordService;
import com.lrc.dentalbackend.utils.MinioUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Resource
    private MinioUtil minioUtil;

    @Resource
    private RecordService recordService;

    @ApiOperation("获取当前时间")
    @GetMapping("/localTime")
    public ResponseResult localTime() {
        return ResponseResult.ok(recordService.localTime());
    }

    @ApiOperation("上传图片接口")
    @PostMapping("/upload")
    public ResponseResult uploadPicture(@RequestPart("file") MultipartFile file){
        // 获取生成唯一的名称
        String onlyFileName = getOnlyFileName(file);
        //上传 minio并返回链接
        String imgUrl = minioUtil.uploadToMinio(file, onlyFileName);
        log.info("上传的图片url为:{}", imgUrl);

        return ResponseResult.ok(imgUrl);

    }

    /**
     * 获取文件并生成唯一名称
     *
     * @param file
     * @return
     */
    protected String getOnlyFileName(MultipartFile file) {
        // 判断文件格式是否为空或图片图片
        if (file == null || file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }
        if (!Objects.requireNonNull(file.getContentType()).startsWith("image/")) {
            throw new RuntimeException("必须为图片");
        }
        // 采用唯一名称
        String filename = file.getOriginalFilename();
        if (StringUtils.isBlank(filename)) {
            throw new RuntimeException("文件名不合法");
        }
        String[] split = filename.split("\\.");
        // 如果分割的不是两串或以上
        if (split.length < 2) {
            throw new RuntimeException("文件名不合法");
        }
        // 获取后缀名
        String lastName = split[split.length - 1];
        // 拼接成唯一名称
        return UUID.randomUUID() + "." + lastName;
    }
}
